package in.iqing.view.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import butterknife.Bind;
import in.iqing.app.R;
import in.iqing.base.BaseActivity;
import in.iqing.control.util.IntentUtil;

/**
 * Created by neavo on 2014/6/28.
 */

public class IndexActivity extends BaseActivity {

	@Bind(R.id.index_wv)
	public WebView indexWV;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_index);
	}

	@Override
	protected void onInitialize(Bundle savedInstanceState) {
		super.onInitialize(savedInstanceState);

		initIndexWV();
		initActionBar();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		showLoading();
		indexWV.loadUrl("http://iqing.coding.io");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		indexWV.loadData("", "text/html", "utf-8");
	}

	@Override
	public void onBackPressed() {
		finish();
		IntentUtil.startActivity(getActivity(), MainActivity.class);
	}

	public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
		boolean consumed = false;

		if (keyCode == KeyEvent.KEYCODE_BACK && indexWV.canGoBack()) {
			consumed = true;
			indexWV.goBack();
		}

		return consumed || super.onKeyDown(keyCode, event);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initIndexWV() {
		indexWV.setWebViewClient(new ExtWebViewClient());
		indexWV.getSettings().setJavaScriptEnabled(true);
	}

	private void initActionBar() {
		if (getActionBar() != null) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar().setDisplayShowHomeEnabled(false);
		}
	}

	private class ExtWebViewClient extends WebViewClient {

		@Override
		public void onPageFinished(WebView view, String url) {
			if (url.equals("http://iqing.coding.io") || url.equals("http://iqing.coding.io/")) {
				showContent();
			} else {
				super.onPageFinished(view, url);
			}
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (url.matches("^.*/\\d+/\\d+.data")) {
				Bundle extras = new Bundle();
				extras.putString("url", url);

				IntentUtil.startActivity(getActivity(), DownloadActivity.class, extras);
			}

			return super.shouldOverrideUrlLoading(view, url);
		}
	}
}
